<template>
  <div class="user-management-container">
    <!-- 搜索栏 -->
    <el-card shadow="never" class="search-box">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input
            v-model="searchForm.phone"
            placeholder="请输入手机号"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户表格 -->
    <el-card shadow="never" class="table-box">
      <div class="table-actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>新增用户
        </el-button>
      </div>
      
      <el-table
        :data="tableData"
        border
        stripe
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="phone" label="手机号" width="150" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="fetchUserData"
          @current-change="fetchUserData"
        />
      </div>
    </el-card>

    <!-- 查看用户对话框 -->
    <el-dialog v-model="viewDialogVisible" title="用户详情" width="50%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="用户ID">{{ currentUser.id }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ currentUser.username }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ currentUser.phone }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ currentUser.email }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentUser.status === 1 ? 'success' : 'danger'">
            {{ currentUser.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentUser.createTime }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="提示"
      width="30%"
    >
      <span>确定要删除用户 "{{ currentUser.username }}" 吗？</span>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {userInfo,deleteUser} from '@/api/user.js'
// 搜索表单
const searchForm = ref({
  username: '',
  phone: ''
})
interface UserDTO  {
  userId: 0,
  username: '',
  phone: '',
  sex:'',
  role:''
}
// 表格数据
const tableData = ref<UserDTO[]>([])
const loading = ref(false)

// 分页配置
const pagination = ref({
  current: 1,
  size: 10,
  total: 0
})

// 当前操作用户
const currentUser = ref<UserDTO>({
    userId: 0,
  username: '',
  phone: '',
  sex:'',
  role:''
})

// 对话框控制
const viewDialogVisible = ref(false)
const deleteDialogVisible = ref(false)

// 获取用户数据
const fetchUserData = async () => {
  try {
    loading.value = true
    // 这里替换为你的API调用
    console.log('查找的pagenum',pagination.value.current);
    console.log('查找的pagesize',pagination.value.size);
    const response = await userInfo({ 
        pageNum:pagination.value.current,
        pageSize: pagination.value.size
      });
    console.log('返回的response是：',response.data);
    tableData.value = response.data.data
    console.log('abcdef');
    // const res = await getUserList({
    //   page: pagination.value.current,
    //   size: pagination.value.size,
    //   ...searchForm.value
    // })
    // 模拟数据
    // const mockData: UserDTO[] = Array.from({ length: 50 }, (_, i) => ({
    //   id: i + 1,
    //   username: `user${i + 1}`,
    //   phone: `138${Math.floor(10000000 + Math.random() * 90000000)}`,
    //   email: `user${i + 1}@example.com`,
    //   status: Math.random() > 0.3 ? 1 : 0,
    //   createTime: new Date(Date.now() - Math.random() * 1e10).toLocaleString()
    // }))
    
    // // 模拟筛选
    // let filteredData = mockData
    // if (searchForm.value.username) {
    //   filteredData = filteredData.filter(item => 
    //     item.username.includes(searchForm.value.username)
    //   )
    // }
    // if (searchForm.value.phone) {
    //   filteredData = filteredData.filter(item => 
    //     item.phone.includes(searchForm.value.phone)
    //   )
    // }
    
//     // 模拟分页
//     const start = (pagination.value.current - 1) * pagination.value.size
//     const end = start + pagination.value.size
//     tableData.value = filteredData.slice(start, end)
//     pagination.value.total = filteredData.length
    
    loading.value = false
  } catch (error) {
     loading.value = false
     ElMessage.error('获取用户数据失败')
   }
 }

// 搜索
const handleSearch = () => {
  pagination.value.current = 1
  fetchUserData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    username: '',
    phone: ''
  }
  handleSearch()
}

// 查看用户
const handleView = (row: UserDTO) => {
  currentUser.value = { ...row }
  viewDialogVisible.value = true
}

// 删除用户
const handleDelete = (row: UserDTO) => {
  currentUser.value = { ...row }
  console.log('当前用户是：',currentUser.value);
  deleteDialogVisible.value = true
}

// 确认删除
const confirmDelete = async () => {
  try {
    // 这里替换为你的API调用
     await deleteUser(currentUser.value.userId)
    ElMessage.success('删除成功')
    deleteDialogVisible.value = false
    fetchUserData()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 新增用户
const handleAdd = () => {
  ElMessage.info('新增用户功能待实现')
}

// 初始化加载数据
onMounted(() => {
  fetchUserData()
})
</script>

<style scoped>
.user-management-container {
  padding: 20px;
}

.search-box {
  margin-bottom: 20px;
}

.table-box {
  margin-bottom: 20px;
}

.table-actions {
  margin-bottom: 15px;
}

.pagination {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}
</style>